package com.huilian.iotbox.data.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@Component
public class ApplicationContextProvider implements ApplicationContextAware {


    private static final Logger log = LoggerFactory.getLogger(ApplicationContextProvider.class);

    private static ApplicationContext applicationContext;

    /**
     * 设置spring上下文
     *
     * @param applicationContext spring上下文
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("spring上下文applicationContext正在初始化,application:{}", applicationContext);
        this.applicationContext = applicationContext;
        log.info("spring上下文applicationContext初始化完成!");
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;

    }

    public static Object getBean(String name) {
        if (applicationContext == null) {
            log.warn("applicationContext是空的");
            return null;
        }
        return getApplicationContext().getBean(name);

    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);

    }
}
